package com.igoal.service;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.igoal.dto.UserDTO;

public class GmailContactServiceImpl extends BaseContactSrevice implements ContactService {
	private Log logger = LogFactory.getLog(GmailContactServiceImpl.class);

	private ContactsService contactService;

	GmailContactServiceImpl() {}

	public List<UserDTO> listContact(String username, String password) {
		boolean authFlag = login(username, password);
		if(authFlag){
			try {
				return getContactEntry(username);
			} catch (Exception e) {
				logger.warn(e);
			}
		}
		return new ArrayList<UserDTO>();
	}

	@Override
	protected boolean login(String username, String password) {
		contactService = new ContactsService("iGoal");
		try {
			contactService.setUserCredentials(username, password);
		} catch (AuthenticationException e) {
			logger.warn(e);
			return false;
		}

		return true;
	}

	private List<UserDTO> getContactEntry(String username) throws IOException, ServiceException {
		// Request the feed
		URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/"+username+"/full?max-results=1000");
		ContactFeed resultFeed = contactService.getFeed(feedUrl, ContactFeed.class);
		
		if(resultFeed.getEntries().size() == 0) return new ArrayList<UserDTO>();
		
		List<UserDTO> users = new ArrayList<UserDTO>();
		
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			ContactEntry entry = resultFeed.getEntries().get(i);
			UserDTO userDTO = new UserDTO();
			if (entry.hasName()) {
				Name name = entry.getName();
				if(name.hasFullName()){
					userDTO.setFirstName(name.getFullName().getValue());
				}else if(name.hasFamilyName()){
					userDTO.setLastName(name.getFamilyName().getValue());
				}
			}
			
			if(entry.getEmailAddresses().size() > 0){
				for (Email email : entry.getEmailAddresses()) {
					if(email.getPrimary()){
						userDTO.setEmail(email.getAddress());
						break;
					}				
				}
				users.add(userDTO);
			}
				
		}
		return users;
	}

}
